<template>
  <div class="app-container">
    <el-card>
      <el-collapse accordion v-model="collapseActiveName" @change="handleChange">
        <el-collapse-item name="open">
          <template #title>
            <p style="font-size: 15px;">事项详细</p>
            <el-icon style="color: #47a1fc;font-size: 18px;">
              <info-filled />
            </el-icon>
          </template>
          <el-form ref="matterRef" :model="matterForm" :rules="rules" label-width="180px">
            <el-row>
              <el-col :span="22">
                <el-form-item label="工作任务" prop="relatedIndicatorOrTaskId">
                  <el-select v-model="matterForm.relatedIndicatorOrTaskId" placeholder="请选择工作任务">
                    <el-option
                      v-for="task in workTaskList"
                      :key="task.targetTaskId"
                      :label="task.targetTaskName"
                      :value="task.targetTaskId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="22">
                <el-form-item label="事项名称" prop="matterName">
                  <el-input v-model="matterForm.matterName" placeholder="请输入事项名称" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="22">
                <el-form-item label="事项内容" prop="matterContent">
                  <el-input type="textarea" v-model="matterForm.matterContent" placeholder="请输入事项内容" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="事项负责人" prop="matterResponsibleId">
                  <el-select v-model="matterForm.matterResponsibleId" placeholder="请选择事项负责人" @change="changeUser($event)">
                    <el-option
                        v-for="item in userList"
                        :key="item.userId"
                        :label="item.nickName"
                        :value="item.userId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="完成期限" prop="completionDeadline">
                  <el-date-picker
                      v-model="matterForm.completionDeadline"
                      type="date"
                      style="width: 100%;"
                      placeholder="请选择完成期限"
                      format="YYYY/MM/DD"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="11">
                <el-form-item label="关联法律" prop="relatedLawId">
                  <el-select v-model="matterForm.relatedLawId" placeholder="请选择" clearable filterable>
                    <el-option
                        v-for="law in related_law"
                        :key="law.value"
                        :label="law.label"
                        :value="law.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="11">
                <el-form-item label="关联制度" prop="relatedPolicyId">
                  <el-select filterable v-model="matterForm.relatedPolicyId" placeholder="请选择" @focus="systemManage" clearable >
                    <el-option
                        v-for="policy in relatedPolicies"
                        :key="policy.value"
                        :label="policy.label"
                        :value="policy.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
<!--            <el-row>-->
<!--              <el-col :span="11">-->
<!--                <el-form-item label="事项关联人" prop="em2">-->
<!--                  <el-input disabled v-model="matterForm.em2" placeholder="请先选择事项负责人"/>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
<!--              <el-col :span="11">-->
<!--                <el-form-item label="归属部门" prop="deptId">-->
<!--                  <el-input disabled v-model="matterForm.dept" placeholder="请先选择事项负责人"/>-->
<!--                </el-form-item>-->
<!--              </el-col>-->
<!--            </el-row>-->
            <el-row>
              <el-col :span="11">
                  <el-form-item label="关键节点类型" prop="workContentType">
                    <el-radio-group v-model="matterForm.workContentType">
                      <el-radio label="0">市场类</el-radio>
                      <el-radio label="1">非市场类</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="11">
                  <el-form-item label="是否成立专班" prop="isSpecialTeamFormed">
                    <el-radio-group v-model="matterForm.isSpecialTeamFormed">
                      <el-radio label="0">是</el-radio>
                      <el-radio label="1">否</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
            </el-row>
          </el-form>
          <div style="text-align: center;">
            <el-button v-show="matterForm.matterId == null" type="primary" @click="submitForm">保 存</el-button>
            <el-button v-show="matterForm.matterId != null" :disabled="matterForm.em4 === '3' || matterForm.em4 === '4' || matterForm.em4 === '5'" type="primary" @click="submitForm">修 改</el-button>
            <el-button type="info" @click="reset" style="margin-left: 50px;">清 空</el-button>
            <el-button type="warning" @click="close" style="margin-left: 50px;">收 缩</el-button>
            <el-button type="danger" @click="closePage" style="margin-left: 50px;">关闭页面</el-button>
          </div>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    <el-card>
      <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" style="margin-top: 10px;">
        <el-form-item prop="matterName">
          <el-input
            style="width: 300px"
            v-model="queryParams.matterName"
            placeholder="请输入事项名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <!-- <el-form-item prop="em4">
          <el-select style="width: 200px" v-model="queryParams.em4" placeholder="请选择状态" clearable>
            <el-option
              v-for="dict in task_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
          >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getMatterList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="matterList" @selection-change="handleSelectionChange"><!-- :span-method="objectSpanMethod" -->
        <el-table-column min-width="2%" type="selection" align="center" />
        <el-table-column min-width="3%" type="index" label="序号" align="center"/>
        <!-- <el-table-column  min-width="10%" label="事项名称" prop="matterName"/> -->
        <el-table-column  min-width="10%" label="事项名称" prop="matterName">
          <template #default="scope">
            <el-text type="primary" style="cursor: pointer" @click="handleUpdate(scope.row)">{{ scope.row.matterName }}</el-text>
          </template>
        </el-table-column>
        <el-table-column min-width="5%" label="负责人" align="center" prop="matterResponsible"/>
        <el-table-column min-width="5%" label="关联人" align="center" prop="em2"/>
        <el-table-column min-width="15%" label="所属部门" align="center" prop="dept"/>
        <el-table-column min-width="6%" label="事项完成期限" align="center" prop="completionDeadline" :formatter="formatDate"/>
        <el-table-column min-width="5%" label="事项状态" align="center">
          <template #default="scope">
            <dict-tag :options="task_status" :value="scope.row.em4"/>
          </template>
        </el-table-column>
        <el-table-column min-width="8%" label="操作" align="center">
          <template #default="scope">
            <el-button-group class="ml-4">
              <el-button type="primary" @click="handleMatter(scope.row)" :disabled="scope.row.em4 !== '1'">派发</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getMatterList"
      />
    </el-card>
  </div>
</template>

<script setup name="createMatter">
import {dataScopeMatterList, listMatter, addMatter, updateMatter, getSystemManage, delMatter, queryById } from "@/api/matter/matter";
import {getTargetTaskList} from "@/api/targetTask/targetTask.js";
import {getUser, listUserNoPage} from "@/api/system/user.js";
import useUserStore from '@/store/modules/user'
const userStore = useUserStore();
const { proxy } = getCurrentInstance();
const { task_status, related_law} = proxy.useDict('task_status', 'related_law');

const matterList = ref([]);
const workTaskList = ref([]);
const loading = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const collapseActiveName = ref('open');
const showSearch = ref(true);
const userList = ref([]);// 存储用户选项
const relatedPolicies = ref([]); // 存储关联制度选项

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    relatedIndicatorOrTaskId: null,
    matterName: null,
    em4: null,
    isPf:'1',
  },
  matterForm: {
    matterId: null,
    matterName: null, //  事项名称
    matterResponsibleId: null, // 事项负责人ID
    matterRelatedPerson: null, // 事项关联人
    matterRelatedPersonId: null, // 事项关联人ID
    em2: null, // 事项关联人
    em4: '1', // 事项状态
    em5: '0', // 事项催办状态
    dept: null,
    deptId: null, // 部门
    relatedLawId: null, // 关联法律
    relatedPolicyId: null, // 关联制度
    relatedIndicatorOrTaskType: '1', //关联指标或任务类型
    relatedIndicatorOrTaskId: null, // 关联指标或任务类型id
    workContentType: '1', // 工作内容类型
    isSpecialTeamFormed: '1', // 是否成立专班
    completionDeadline: null, // 事项完成期限
  },
  rules: {
    matterName: [{required: true, message: "事项名称不能为空", trigger: "blur"}],
    matterResponsibleId: [{required: true, message: "事项负责人不能为空", trigger: "blur"}],
    em2: [{required: true, message: "事项关联人不能为空", trigger: "blur"}],
    deptId: [{required: true, message: "归属部门不能为空", trigger: "blur"}],
    relatedIndicatorOrTaskId: [{required: true, message: "工作任务不能为空", trigger: "change"}],
    workContentType: [{required: false}],
    isSpecialTeamFormed: [{required: false}],
    completionDeadline: [{required: true, message: "完成期限不能为空", trigger: "change"}]
  },
});

const { queryParams, matterForm, rules } = toRefs(data);

/** 查询任务列表 */
function getTaskList() {
  loading.value = true;
  getTargetTaskList(queryParams.value).then(response => {
    workTaskList.value = response.data;
  });
}

/** 查询事项列表 */
function getMatterList() {
  loading.value = true;
  dataScopeMatterList(queryParams.value).then(response => {
    matterList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询制度列表 */
function getManageList() {
  getSystemManage().then(response => {
    relatedPolicies.value = response.data
  });
}
/** 查询用户列表 */
function getUserList() {
  let data = {queryDept: true};
  listUserNoPage(data).then(res => {
    userList.value = proxy.handleTree(res.data, "userId");
  });
}

/** 选中用户 */
function changeUser(value){
  const user = userList.value.find(item => item.userId === value);
  matterForm.value.em2 = user.nickName
  matterForm.value.matterRelatedPerson = user.nickName
  matterForm.value.dept = user.dept.deptName
  matterForm.value.deptId = user.dept.deptId
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getMatterList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.matterId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 关闭操作 */
function close() {
  collapseActiveName.value = ''
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  handleChange('open');
}

/** 修改按钮操作 */
function handleUpdate(row) {
  const matterId = row.matterId || ids.value[0];
  loading.value = true;
  queryById(matterId).then(response => {
    matterForm.value = response.data;
    loading.value = false;
    handleChange('open');
  })
}

/** 删除按钮操作 */
function handleDelete() {
  const _matterIds = ids.value;
  console.log(_matterIds);
  proxy.$modal.confirm('是否确认删除数据？').then(function() {
    return delMatter(_matterIds);
  }).then(() => {
    getMatterList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 派发事项 */
function handleMatter(row){
  updateMatter({matterId : row.matterId, em4: '2'}).then(response => {
    proxy.$modal.msgSuccess("派发成功");
    reset();
    getMatterList()
  })
}

// 表单重置
function reset() {
  matterForm.value = {
    matterId: null,
    matterName: null, //  事项名称
    matterResponsibleId: null, // 事项负责人ID
    matterRelatedPerson: null, // 事项关联人
    matterRelatedPersonId: null, // 事项关联人ID
    em2: null, // 事项关联人
    em4: '1', // 事项状态
    em5: '0', // 事项催办状态
    dept: null,
    deptId: null, // 部门
    relatedLawId: null, // 关联法律
    relatedPolicyId: null, // 关联制度
    relatedIndicatorOrTaskType: '1', //关联指标或任务类型
    relatedIndicatorOrTaskId: null, // 关联指标或任务类型id
    workContentType: '1', // 工作内容类型
    isSpecialTeamFormed: '1', // 是否成立专班
    completionDeadline: null, // 事项完成期限
  }
  proxy.resetForm("matterRef");
}
//组件上点击事件
function handleChange(value) {
  'open' === value ? collapseActiveName.value = 'open' : collapseActiveName.value = ''
}
/** 关闭按钮 */
function closePage() {
  proxy.$tab.closePage();
};
/** 提交按钮 */
function submitForm() {
  proxy.$refs["matterRef"].validate(valid => {
    if (valid) {
      loading.value = true;
      if (matterForm.value.matterId != null) {
        updateMatter(matterForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          getMatterList();
        });
      } else {
        addMatter(matterForm.value).then(response => {
          proxy.$modal.msgSuccess("保存成功");
          getMatterList();
        });
      }
    }
  });
}

// 使用 watch 来监听 tabData 的变化
watch(() => matterForm.value.relatedIndicatorOrTaskId, (newVal) => {
  queryParams.value.relatedIndicatorOrTaskId = newVal;
  getMatterList(data.queryParams)
}, {
  immediate: true, // 组件加载时立即执行一次回调函数
});
const route = useRoute();
(() => {
  const targetTaskId = route.query.targetTaskId;
  matterForm.value.relatedIndicatorOrTaskId = targetTaskId === undefined ? null : Number(targetTaskId)
  getUser(userStore.id).then(res => {
    if (res.data && res.data.dept && res.data.dept.deptType) {
      res.data.dept.deptType === '1' ? matterForm.value.workContentType = '1' : matterForm.value.workContentType = '0'
    }
  });
})();
getManageList();
getUserList();
getTaskList();
getMatterList();
</script>
<style scoped>
.app-container {
  padding: 10px;
}

:deep(.el-card .el-card__body) {
  padding: 10px  !important
}

.el-collapse {
  border: none;
  box-shadow: none;
}

:deep(.el-collapse-item__header) {
  border-bottom: none;
}

.el-collapse-item__wrap {
  border: none;
}
</style>
